package com.imu.wys.controller;

import com.imu.wys.model.User;
import com.imu.wys.service.UserService;
import com.imu.wys.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/tuser")
public class UserControllerCache {

    @Autowired
    private UserService userService;

    @Autowired
    RedisUtil redisUtil;

    @RequestMapping(value = {"login"})
    public ModelAndView login(HttpServletRequest request, String username, String password) {
        ModelAndView ma = new ModelAndView();
        String shixiaoKey = "shiXiaoKey"+username;

        if(redisUtil.hasKey(shixiaoKey)){
            ma.setViewName("tlogin");
            ma.getModel().put("msg", "用户已锁定，请在"+redisUtil.getExpire(shixiaoKey)+"s后登陆");
            return ma;
        }
        User user = userService.findByUserName(username);
        if (null != user) {
            if (user.getPassword().equals(password)) {
                request.getSession().setAttribute("existUser", user);
                ma.addObject("user", user);
                ma.setViewName("tmain");
            } else {
                ma.setViewName("tlogin");
                ma.getModel().put("msg", "密码错误!");
            }
        } else {
            ma.setViewName("tlogin");
            ma.getModel().put("msg", "用户名不存在!");
        }
        return ma;
    }


    @RequestMapping(value = {"register"})
    public ModelAndView register(HttpServletRequest request, String username, String password) {
        ModelAndView ma = new ModelAndView();
        User user = userService.findByUserName(username);
        if (user == null) {
            User registerUser = new User();
            registerUser.setUsername(username);
            registerUser.setPassword(password);
            try {
                userService.insertUser(registerUser);
                ma.setViewName("tlogin");
                ma.addObject("user", registerUser);
                ma.getModel().put("msg", "注册成功前往登录！");
            } catch (Exception e) {
//                System.out.println(e.getMessage());
                ma.setViewName("tregister");
                ma.getModel().put("msg", "注册失败！");
            }

        } else { //用户名存在
            ma.setViewName("tregister");
            ma.getModel().put("msg", "用户名已存在!");
        }
        return ma;
    }
}
